package cn.com.dashihui.web.rabbitmq;


import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import cn.com.dashihui.web.common.RabbitMQCode;


public class MsgSend {
	
	public static boolean send(String id,String queueName){
		Connection connection = MQFactory.getConnection();
		Channel channel = null;
		try {
			channel = connection.createChannel();
			/*
			 * 声明交换机及其类型
			 * 交换机名称
			 * 交换机类型
			 */
			channel.exchangeDeclare(RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.EXCHANGE_TYPE);
			//开启事务
			channel.txSelect();
			/*
			 * 交换机名称
			 * 路由键
			 * 其他属性
			 * 消息内容
			 */
			if(RabbitMQCode.Code.QUEUE_UP.equals(queueName)){
				channel.basicPublish(RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_UP, null, id.getBytes());
			}else{
				channel.basicPublish(RabbitMQCode.Code.EXCHANGENAME, RabbitMQCode.Code.KEY_DOWN, null, id.getBytes());
			}
			//提交
			channel.txCommit();
			return true;
		} catch (IOException e) {
			try {
				//回滚
				channel.txRollback();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//事务回滚
			return false;
		}finally {
			if(channel!=null){
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (TimeoutException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
